<?php

namespace app\partneradmin\library;

use app\partneradmin\model\Partner;
use app\partneradmin\model\PartnerAdmin;
use app\partneradmin\model\PartnerAdminLoginLog;
use super\Random;
use think\Cache;
use think\Exception;
use think\exception\DbException;
use think\Request;


class Auth
{
    protected $_error = '';
    protected $logined = false; //登录状态
    protected $username;
    protected $keepTime = 3600;


    public function __get($name)
    {
        return Cache::store('redis')->get('partneradmin.' . $name);
    }

    /**
     * 合作方管理员登录
     *
     * @param string $params 参数
     * @param int $keeptime 有效时长
     * @return  boolean
     * @throws Exception
     * @throws DbException
     */
    public function login($params, $keeptime = 0)
    {
        $partneradmin = PartnerAdmin::get(['username' => $params['account']]);

        if (!$partneradmin) {
            $this->setError('不存在的账户');
            return false;
        }

        $partner = Partner::get($partneradmin['partner_id']);
        if ($partner['status'] == 0) {
            $this->setError('该合作方已被禁用!');
            return false;
        }
        if ($partner['is_del'] == 1) {
            $this->setError('不存在的合作方!');
            return false;
        }
        $isLogin = Cache::store('redis')->get($partneradmin['token']);
        if ($isLogin) {
            if (!$params['google_code']) {
                $this->setError('谷歌验证码必须！');
                return false;
            }
//            if ($params['google_code'] !== '111222') {
                $checkGoogleCodeData['google_code'] = $params['google_code'];
                $checkGoogleCodeData['secret'] = $partneradmin['google_secret_key'];
                $checkGoogleCodeRes = $this->checkGoogleCode($checkGoogleCodeData);
                if (!$checkGoogleCodeRes) {
                    $this->setError('谷歌验证码不正确！');
                    return false;
                }
//            }

            $isLogin['token_expiration_time'] = time() + $keeptime;
            Cache::store('redis')->set($partneradmin->token, $isLogin, $keeptime);
            return $isLogin;
        }

        $loginlog['partner_admin_id'] = $partneradmin['id'];
        $loginlog['logintime'] = time();
        $loginlog['loginip'] = request()->ip();
        $loginlog['status'] = 0;
        $loginlog['create_time'] = time();
        if ($partneradmin['status'] == 0) {
            PartnerAdminLoginLog::create($loginlog);
            $this->setError('账户已禁用');
            return false;
        }

        if ($partneradmin->password != md5(md5($params['passwd']) . $partneradmin['salt'])) {
            PartnerAdminLoginLog::create($loginlog);
            $this->setError('密码错误');
            return false;
        }
//        if ($params['google_code'] !== '111222') {
            if ($partneradmin['is_bind_google'] == 1) {
                if (!$params['google_code']) {
                    $this->setError('谷歌验证码必须！');
                    return false;
                }
                $checkGoogleCodeData['google_code'] = $params['google_code'];
                $checkGoogleCodeData['secret'] = $partneradmin['google_secret_key'];
                $checkGoogleCodeRes = $this->checkGoogleCode($checkGoogleCodeData);
                if (!$checkGoogleCodeRes) {
                    $this->setError('谷歌验证码不正确！');
                    return false;
                }
            }
//        }


        $partneradmin->logintime = time();
        $partneradmin->loginip = request()->ip();
        $partneradmin->token = 'partner' . Random::uuid();
        $saveAdmin = $partneradmin->save();

        $loginlog['token'] = $partneradmin->token;
        if ($saveAdmin) {
            $loginlog['status'] = 1;
        }
        $loginlog['token_expiration_time'] = time() + $keeptime;
        PartnerAdminLoginLog::create($loginlog);

        $data = $partneradmin->toArray();
        $data['token_expiration_time'] = $loginlog['token_expiration_time'];
        Cache::store('redis')->set($partneradmin->token, $data, $keeptime);
        return $partneradmin->token;
    }

    /**
     * 获取当前账户信息
     *
     */
    public function getUserInfo($admin_token)
    {
        $admin = Cache::store('redis')->get($admin_token);
        return $admin;
    }

    /**
     * 检测token是否可用
     *
     */
    public function checkToken($token = null)
    {
        $keeplogin = Cache::store('redis')->get($token);
        if (!$keeplogin) {
            return false;
        }
        if (empty($keeplogin['partner_id'])) {
            return false;
        }
        if ($keeplogin['token_expiration_time'] < time()) {
            Cache::store('redis')->rm($token);
            return false;
        }
        $keeplogin['token_expiration_time'] = time() + $this->keepTime;
        Cache::store('redis')->set($token, $keeplogin, $this->keepTime);
        return true;
    }

    /**
     * 退出登录
     *
     */
    public function logout($token)
    {
        $admin = PartnerAdmin::get(['token' => $token]);
        if ($admin) {
            $admin->token = '';
            $admin->save();
        }
        $this->logined = false; //重置登录状态
        Cache::store('redis')->rm($token);
        return true;
    }

    /**
     * 谷歌验证器效验code
     *
     */
    public function checkGoogleCode($params)
    {
        $ga = new \google\GoogleAuthenticator;
        $code = $params['google_code'];
        $secret = $params['secret'];
        $checkResult = $ga->verifyCode($secret, $code, 2);
        if (!$checkResult) {
            return false;
        }
        return true;
    }

    /**
     * 获取谷歌验证器验证信息
     *
     */
    public function getGoogleData()
    {
        $ga = new \google\GoogleAuthenticator;
        $secret = $ga->createSecret();

        $qrCodeUrl = $ga->getQRCodeGoogleUrl('SUPER_PARTNER_ADMIN_APP', $secret);
        $data['qrcode'] = $qrCodeUrl;
        $data['secret'] = $secret;
        return $data;
    }

    /**
     * 检测当前控制器和方法是否匹配传递的数组
     *
     * @param array $arr 不需要验证权限的数组
     * @return bool
     */
    public function match($arr = [])
    {
        $request = Request::instance();
        $arr = is_array($arr) ? $arr : explode(',', (string)$arr);
        if (!$arr) {
            return false;
        }

        $arr = array_map('strtolower', $arr);
        // 是否存在
        if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
            return true;
        }

        // 没找到匹配
        return false;
    }


    /**
     * 设置错误信息
     *
     * @param string $error 错误信息
     * @return Auth
     */
    public function setError($error)
    {
        $this->_error = $error;
        return $this;
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError()
    {
        return $this->_error ? $this->_error : '';
    }
}
